document.addEventListener('DOMContentLoaded', function() {
    const editButtons = document.querySelectorAll('.edit-btn');
    const saveButtons = document.querySelectorAll('.save-btn');

    editButtons.forEach((button, index) => {
        button.addEventListener('click', function() {
            const row = this.closest('tr');
            const cells = row.querySelectorAll('.editable');
            cells.forEach(cell => {
                cell.contentEditable = true;
            });
            this.style.display = 'none';
            saveButtons[index].style.display = 'inline';
        });
    });

    saveButtons.forEach((button, index) => {
        button.addEventListener('click', function() {
            const row = this.closest('tr');
            const dataId = row.getAttribute('data-id');
            const cells = row.querySelectorAll('.editable');
            const updateData = {};
            cells.forEach(cell => {
                const field = cell.getAttribute('data-field');
                updateData[field] = cell.textContent;
            });

            fetch('/polls/update_character/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                },
                body: JSON.stringify({ id: dataId, data: updateData })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    cells.forEach(cell => {
                        cell.contentEditable = false;
                    });
                    this.style.display = 'none';
                    editButtons[index].style.display = 'inline';
                } else {
                    alert('保存失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        });
    });
});